package main

import (
	mysqlDb "DouBan/db/mysql"
	"DouBan/db/redis"
	"DouBan/model"
	"DouBan/route"
	"DouBan/utils"
	"DouBan/utils/logger"
	"context"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"
)

var (
	err error
)

func catchExit() {
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
	<-signalChan
	logger.InfoLn("老子退出了")
	mysqlDb.Exit()
	redis.Exit()
	os.Exit(1)
}

func catchHouseChange() {
	for {
		redisClient := redis.MasterClient()
		ctx := context.Background()
		lastTopicId, _ := redisClient.Get(ctx, "lastTopicId").Uint64()
		nowTopicId, _ := redisClient.Get(ctx, "nowTopicId").Uint64()
		if nowTopicId > lastTopicId {
			subscribeSelectResultList := make([]model.SubscribeSelectResult, 0)
			mysqlDb.MasterDb().Debug().Select("t1.topic_id", "t3.email").Table("topic as t1").
				Joins("join subscribe as t2 on t1.rent_type = t2.rent_type and t1.house_type = t2.house_type and t1.city = t2.city").
				Joins("join user as t3 on t2.user_id = t3.id").Where("t1.id > ?", lastTopicId).Find(&subscribeSelectResultList)
			cache := make(map[string][]string)
			for _, subscribeSelectResult := range subscribeSelectResultList {
				if cache[subscribeSelectResult.Email] == nil {
					cache[subscribeSelectResult.Email] = []string{}
				}
				url := fmt.Sprintf("https://www.douban.com/group/topic/%s", subscribeSelectResult.TopicId)
				cache[subscribeSelectResult.Email] = append(cache[subscribeSelectResult.Email], fmt.Sprintf(`<a href="%s">%s</a></br>`, url, url))
			}
			for k := range cache {
				if len(cache[k]) > 0 {
					go utils.SendEmail([]string{k}, "有房子了", strings.Join(cache[k], "\n"))
				}
			}
			redisClient.Set(ctx, "lastTopicId", nowTopicId, -1)
		}
		time.Sleep(time.Minute)
	}
}

func start() {
	go catchExit()
	if err = logger.Init("./config/logger.toml"); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	if err = mysqlDb.Init("./config/mysql_db.toml"); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	if err = redis.Init("./config/redis.toml"); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	go catchHouseChange()
	route.StartServer()
}

func main() {
	start()
}
